package com.drug.mingkang.service.impl;

import com.drug.mingkang.mapper.AuditRecordMapper;
import com.drug.mingkang.mapper.ImmSellMapper;
import com.drug.mingkang.mapper.SellDetailMapper;
import com.drug.mingkang.model.*;
import com.drug.mingkang.model.vo.EChartsVo;
import com.drug.mingkang.model.vo.SalesProfitVo;
import com.drug.mingkang.model.vo.SalesStatisticsVo;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.*;
import com.drug.mingkang.utils.AuditStatus;
import com.drug.mingkang.utils.Line;
import com.drug.mingkang.utils.ResponseMessage;
import com.drug.mingkang.utils.Tools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * (ImmSell)表服务实现类
 *
 * @author wutao
 * @since 2020-08-11 12:00:14
 */
@Service("immSellService")
public class ImmSellServiceImpl implements ImmSellService {
    @Resource
    private ImmSellMapper immSellMapper;

    @Resource
    private SellDetailService sellDetailService; //销售明细

    @Resource
    private ImmSellService immSellService; //销售

    @Resource
    private ImmRepertoryService immRepertoryService; //库存

    @Resource
    private ImmAppearService immAppearService; //出库明细

    @Resource
    private ImmFinanceService immFinanceService; //财务

    @Resource
    private ImmRicherService immRicherService; //财务明细

    @Resource
    private HttpSession session;

    /**
     * 分公司销售明细服务
     */
    @Resource
    private SellDetailMapper sellDetailMapper;

    /**
     * 审核服务
     */
    @Resource
    private AuditRecordMapper auditRecordMapper;

    /**
     * 工具类服务
     */
    @Resource
    private Tools tools;

    @Resource
    private ResponseMessage responseMessage;



    /**
     * 通过ID查询单条数据
     *
     * @param sellId 主键
     * @return 实例对象
     */
    @Override
    public ImmSell queryById(String sellId) {
        return this.immSellMapper.queryById(sellId);
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public List<ImmSell> queryAllByLimit(ImmSell immSell, String companyId) {
        return this.immSellMapper.queryAllByLimit(immSell,companyId);
    }

    @Override
    public List<ImmSell> queryAllByLimits(ImmSell immSell, String companyId,String status) {
        return this.immSellMapper.queryAllByLimits(immSell,companyId,status);
    }

    /**
     * 统计
     *
     * @return
     */
    public int countId(ImmSell immSell, String companyId){
        return immSellMapper.countId(immSell,companyId);
    }
    public int countIds(ImmSell immSell, String companyId){
        return immSellMapper.countIds(immSell, companyId);
    }

    /**
     * 新增数据
     *
     * @param immSell 实例对象
     * @return 实例对象
     */
    @Override
    public ImmSell insert(ImmSell immSell) {
        this.immSellMapper.insert(immSell);
        return immSell;
    }

    /**
     * 修改数据
     *
     * @param immSell 实例对象
     * @return 实例对象
     */
    @Override
    public ImmSell update(ImmSell immSell) {
        this.immSellMapper.update(immSell);
        return this.queryById(immSell.getSellId());
    }

    /**
     * 通过主键删除数据
     *
     * @param sellId 主键
     * @return 是否成功
     */
    @Override
    public int deleteById(String sellId) {
        return this.immSellMapper.deleteById(sellId);
    }

    @Override
    public int updateStatus(String sellId) {
        return this.immSellMapper.updateStatus(sellId);
    }

    /**
     * 根据年份查询总(分)公司销售前十销售量药品
     * @param page    页
     * @param limit     条
     * @param salesYear    年份
     * @param companyId     分公司Id
     * @return
     */
    @Override
    public List<EChartsVo> selectMarketFrontShi(Integer page, Integer limit, String salesYear, String companyId) {
        return this.immSellMapper.selectMarketFrontShi((page - 1) * limit, limit, salesYear, companyId);
    }

    /**
     * 根据年份查询总(分)公司 销售总金额与成本总金额对比图 与  销售总金额及毛利对比图 (实现销售量折线统计图)
     * @param salesYear  年份
     * @param companyId   分公司Id
     * @return
     */
    @Override
    public Map<String, Object> findTotalCostAllPriceAndSalesProfit(String salesYear, String companyId) {
        //创建一个月份String型数组
        String[] month = new String[]{"1","2","3","4","5","6","7","8","9","10","11","12"};
        //创建一个销售总金额每月long型数组
        Long[] totalSales = new Long[12];
        //创建一个销售总成本每月long型数组
        Long[] cost = new Long[12];
        //创建一个销售毛利每月long型数组
        Long[] grossMargin = new Long[12];
        //查询分公司销售里面的查询一年内每月销售数据的方法
        List<SalesProfitVo> totalCostAllPriceAndSalesProfit = this.immSellMapper.findTotalCostAllPriceAndSalesProfit(salesYear, companyId);
        for (int i = 0; i < month.length; i++) {
            for (SalesProfitVo salesProfitVo : totalCostAllPriceAndSalesProfit) {
                //判断是否有这个月的销售
                if (month[i].equals(salesProfitVo.getMonth())) {
                    totalSales[i] = salesProfitVo.getTotalSales();
                    cost[i] = salesProfitVo.getCost();
                    grossMargin[i] = salesProfitVo.getGrossMargin();
                    break;
                } else {
                    totalSales[i] = Long.valueOf(0);
                    cost[i] = Long.valueOf(0);
                    grossMargin[i] = Long.valueOf(0);
                }
            }
            //没有数据返回[0,0,0,0]
            if(totalCostAllPriceAndSalesProfit.size()<=0){
                totalSales[i] = Long.valueOf(0);
                cost[i] = Long.valueOf(0);
                grossMargin[i] = Long.valueOf(0);
            }
        }
        //创建一个map集合
        Map<String, Object> map = new ConcurrentHashMap<String, Object>();
        //销售总金额
        map.put("totalSales",totalSales);
        //销售总成本
        map.put("cost", cost);
        //销售毛利
        map.put("grossMargin",grossMargin);
        return map;
    }

    @Override
    public Map<String, Object>  findAllSalesStatistics(SalesStatisticsVo salesStatisticsVo,  String status) {
        //根据年份查询分公司销售(每年每月的总销售量)(每月药品销售数量)
        List<SalesStatisticsVo> allSalesStatistics = this.immSellMapper.findAllSalesStatistics(salesStatisticsVo);
        //根据年份查询总公司销售药品总条数
        int drugCount = this.immSellMapper.findAllSalesStatisticsCount(salesStatisticsVo);

        //判断，如果num=1，则调用实现销量折线统计图的方法，如果为2，则调用实现销售排行统计表的方法
        if("1".equals(status)){
            //调用实现销量排行折线统计图的方法，传入总公司销售集合和销售量前十药品集合
            return salesDrugAllBeforeTen(allSalesStatistics);
        }else{
            //调用实现销售排行统计表的方法，传入总公司销售集合和药品总条数
            return tools.limit(allSalesStatistics, drugCount);
        }
    }

    /**
     * 分公司批发审核
     * @param immSell 分公司批发
     * @param auditRecord 审核表
     * @param session 当前会话
     * @return
     */
    @Override
    public ResponseMessage updateWholesaleIsva(ImmSell immSell, AuditRecord auditRecord, HttpSession session) {
        System.out.println("ImmSell ============ " + immSell);
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        //取分公司id
        String immName = perUsers.getCompanyId();
        //修改审核状态
        immSellMapper.fupdate(immSell.getSellId(), immSell.getIsva(),"1");
        //审核表添加记录
        //添加审核人
        auditRecord.setAuditor(perUsers.getUserName());
        //添加业务id
        auditRecord.setBusinessId(immSell.getSellId());
        //判断是否为分公司总经理通过 分公司财务加 分公司减库存  并且保存出入帐明细
        if(String.valueOf(AuditStatus.YES_FGSZJL.status).equals(String.valueOf(immSell.getIsva()))) {
            /* 减库存 */
            List<ImmAppear> immAppearList = new ArrayList<>();
//            List<ImmRicher> immRicherList = new ArrayList<>();

            //根据销售id查询销售明细
            List<SellDetail> list = sellDetailMapper.findBySellId(immSell.getSellId());
            //根据销售id查询查询ImmSell所有信息
            ImmSell ims = immSellMapper.queryById(immSell.getSellId());

            //查询分公司ID
            ImmFinance immf = immFinanceService.findByImmName(immName);
            /*减库存 加财务*/
            for(int i = 0; i < list.size(); i++){
                //new ImmAppear and ImmRicher
                ImmAppear immApp= new ImmAppear();
//                ImmRicher immRicher= new ImmRicher();
                SellDetail sellDetail= list.get(i);
                //销售数量不能为空
                if(sellDetail.getDetailCount() != null){
                    immApp.setAppearCount(sellDetail.getDetailCount());
                    immApp.setDrugId(sellDetail.getDrugId());
                    //修改库存数量
                    ImmRepertory imma = immRepertoryService.updateOne(immApp,immName);
                    immApp.setRepertory(imma.getRepertoryId());
                    immApp.setStatus("2");
                    immApp.setOperator(perUsers.getUserName());
                    immAppearList.add(immApp);

                }
            }
            //批量增加
            immAppearService.insertBatch(immAppearList);

            ImmRicher immRicher= new ImmRicher();

            immRicher.setDrugId(immSell.getSellId());  //取销售ID
            immRicher.setRicherMoney(ims.getSellMonty()); //取销售总金额
            //修改财务金额
            immFinanceService.updateOne(immRicher,immName);
            //分店ID
            immRicher.setFinanceId(immf.getFinanceId());
            immRicher.setOperator(perUsers.getUserName());
            immRicher.setIsva(1);

            immRicherService.insert(immRicher);
//            immRicherService.insertBatch(immRicherList);

        }
        return auditRecordMapper.insertSelective(auditRecord) > 0 ? ResponseMessage.success("审核成功") : ResponseMessage.error("审核失败");
    }

    /**
     * 实现销量排行折线统计图
     * @param allSalesStatistics    总公司销售(每年每月的总销售量)(每月药品销售数量)
     * @return  Map
     */
    private Map<String, Object> salesDrugAllBeforeTen(List<SalesStatisticsVo> allSalesStatistics) {
        //创建一个list集合
        List<Line> listLine = new ArrayList<Line>();
        //判断集合是否为空
        if(allSalesStatistics.size()<=0){
            //循环遍历list集和
            for(int i=0;i<10;i++){
                //创建一个int型数组
                int[] num = new int[12];
                //创建一个折线统计图模型
                Line line = new Line();
                //给折线统计图模型赋值
                line.setName("");
                line.setStack("销量");
                line.setType("line");
                //给1~12月赋值
                for(int j=0;j<12;j++){
                    //给num数组赋值
                    num[j] = 0;
                }
                //给折线统计图模型里面的data数组赋值
                line.setData(num);
                //将折线统计图模型添加到listLine集合中
                listLine.add(line);
            }
        }else{
            for (int i = 0; i < allSalesStatistics.size(); i++) {
                //创建一个int型数组（方便存每月销量）
                int[] num = new int[12];
                //创建一个折线统计图模型
                Line line = new Line();
                //给折线统计图模型赋值
                line.setName(allSalesStatistics.get(i).getDrugName());
                line.setStack("销量");
                line.setType("line");
                //月份赋值
                num[0] = allSalesStatistics.get(i).getOneMonth();
                num[1] = allSalesStatistics.get(i).getTwoMonth();
                num[2] = allSalesStatistics.get(i).getThreeMonth();
                num[3] = allSalesStatistics.get(i).getFourMonth();
                num[4] = allSalesStatistics.get(i).getFiveMonth();
                num[5] = allSalesStatistics.get(i).getSixMonth();
                num[6] = allSalesStatistics.get(i).getSevenMonth();
                num[7] = allSalesStatistics.get(i).getEightMonth();
                num[8] = allSalesStatistics.get(i).getNineMonth();
                num[9] = allSalesStatistics.get(i).getTenMonth();
                num[10] = allSalesStatistics.get(i).getElevenMonth();
                num[11] = allSalesStatistics.get(i).getTwelveMonth();
                //给折线统计图模型里面的data数组赋值
                line.setData(num);
                //将折线统计图模型添加到listLine集合中
                listLine.add(line);
            }

        }
        String[] drugAllName = null;
        //前十药品名称
        if(allSalesStatistics.size()<=0){
            drugAllName =new String[10];
            for (int i = 0; i < 10; i++) {
                drugAllName[i] = "";
            }
        }else{
            drugAllName =new String[allSalesStatistics.size()];
            for (int i = 0; i < allSalesStatistics.size(); i++) {
                drugAllName[i] = allSalesStatistics.get(i).getDrugName();
            }
        }
        //创建一个map集合
        Map<String,Object> map = new HashMap<String,Object>();
        //前十药品数组
        map.put("drugAllName", drugAllName);
        map.put("list", listLine);
        return map;
    }

}